package com.qxy.hot1;


// 思路：遍历一遍看数量 n ， n/k 就是 loop 每次 loop 先保存指向下一次loop的头结点 固定对 k个链表反转。 2n
 // 
public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        int nodeNums=0;
        ListNode dummyNode = new ListNode(-1);
        dummyNode.next = head;
        while(dummyNode.next!=null){
            dummyNode = dummyNode.next;
            nodeNums++;
        }
        if(nodeNums<k){ return head;}
        // 保证翻转一次且k>0 ,dummyNode失效，上面代码没用了
        ListNode newHead = new ListNode(-1);
        newHead.next = head;
        ListNode nextHead = new ListNode(-1);
        nextHead = head;
        int count = k;
        int loop = nodeNums/k;
        while(k>0){
            newHead = newHead.next;
            k--;
        }
        while(loop>0){
            // cur指向当前迭代的头结点
            ListNode cur = nextHead;
            ListNode pre = null;
            int iteratorNums = count;
            //双指针+临时节点,指定迭代次数实现链表反转
            while(iteratorNums>0){
                ListNode temp = cur.next;
                cur.next = pre;
                pre = cur;
                cur = temp;
                iteratorNums--;
            }
            //此时cur为下一个头结点，更新nextHead
            nextHead = cur;
            //迭代后尾节点连接下一个头结点 区分loop == 1
            int counts = count;
            ListNode secondHead = nextHead;
            if(loop == 1){
                for (int i = 1; i < counts; i++) {
                    pre = pre.next;
                }
                pre.next = cur;
            }else {

                for (int i = 1; i < counts; i++) {
                    pre = pre.next;
                    secondHead = secondHead.next;
                }
                pre.next = secondHead;
            }
            loop--;
        }
        return newHead;
    }
}